from flask import Flask, request, jsonify
from datetime import datetime
from flask_cors import CORS
import io
import base64
import matplotlib.pyplot as plt

app = Flask(__name__)
CORS(app)

# 模拟医生账号
doctors = {'dr001': '123456'}

# 存储疼痛记录的内存存储（生产请替换为数据库）
pain_history = []
# 患者备注存储
patient_notes = {}


@app.route('/posture_score', methods=['GET'])
def posture_score():
    # 模拟姿势评分
    score = 8.5
    # 返回纯文本，便于前端不使用 JSON.parse
    return str(score)


@app.route('/record_pain', methods=['POST'])
def record_pain():
    data = request.json
    record = {
        'patient': data.get('patient'),
        'timestamp': datetime.now().isoformat(),
        'intensity': data.get('intensity'),
        'location': data.get('location'),
        'description': data.get('description')
    }
    pain_history.append(record)
    print(f"[疼痛记录] {record}")
    # 返回纯文本确认，简化前端解析
    return 'ok'


@app.route('/pain/history', methods=['GET'])
def pain_history_api():
    # 返回最近的疼痛记录列表
    return jsonify({'history': pain_history})


@app.route('/patients', methods=['GET'])
def patients_list():
    # 返回所有已知患者 ID（去重）
    ids = set()
    for r in pain_history:
        pid = r.get('patient')
        if pid:
            ids.add(pid)
    # 如果没有数据，返回示例患者
    if len(ids) == 0:
        return 'patient001,patient002'
    return ','.join(sorted(list(ids)))


@app.route('/patients/<patient_id>/info', methods=['GET'])
def patient_info(patient_id):
    # 返回指定患者的历史记录和备注
    arr = [r for r in pain_history if r.get('patient') == patient_id]
    notes = patient_notes.get(patient_id, [])
    return jsonify({'patient': patient_id, 'history': arr, 'notes': notes})


@app.route('/patients/<patient_id>/note', methods=['POST'])
def add_patient_note(patient_id):
    data = request.json
    note_text = data.get('note') if data else None
    if not note_text:
        return 'fail|no note', 400
    entry = {'note': note_text, 'timestamp': datetime.now().isoformat()}
    if patient_id not in patient_notes:
        patient_notes[patient_id] = []
    patient_notes[patient_id].append(entry)
    print(f"[患者备注] {patient_id} -> {entry}")
    return 'ok'


@app.route('/patients/<patient_id>/history', methods=['GET'])
def patient_history(patient_id):
    # 返回指定患者的历史记录（从内存中筛选），如果没有则返回示例数据
    arr = [r for r in pain_history if r.get('patient') == patient_id]
    if len(arr) == 0:
        # 生成示例数据
        sample = []
        base_vals = [2, 4, 3, 5, 4]
        for i, v in enumerate(base_vals):
            sample.append({
                'patient': patient_id,
                'timestamp': (datetime.now()).isoformat(),
                'intensity': v,
                'location': '腰部',
                'description': '示例历史'
            })
        return jsonify({'history': sample})
    return jsonify({'history': arr})


@app.route('/patients/<patient_id>/trend', methods=['GET'])
def patient_trend(patient_id):
    # 根据患者历史绘制趋势图
    arr = [r for r in pain_history if r.get('patient') == patient_id]
    if len(arr) == 0:
        # 如果没有真实数据，生成示例折线
        ys = [2, 4, 3, 5, 4]
    else:
        ys = [r.get('intensity', 0) for r in arr]

    xs = list(range(1, len(ys) + 1))

    plt.figure(figsize=(4, 2.5))
    plt.plot(xs, ys, marker='o')
    plt.title(f'患者 {patient_id} 疼痛强度趋势')
    plt.xlabel('记录')
    plt.ylabel('强度')
    plt.grid(True, linestyle='--', alpha=0.5)

    buf = io.BytesIO()
    plt.tight_layout()
    plt.savefig(buf, format='png')
    plt.close()
    buf.seek(0)
    img_b64 = base64.b64encode(buf.read()).decode('utf-8')
    return img_b64


@app.route('/pain/trend', methods=['GET'])
def pain_trend():
    # 根据 intensity 绘制折线图并返回 base64 图像
    if len(pain_history) == 0:
        return jsonify({'error': 'no data'}), 400

    xs = list(range(1, len(pain_history) + 1))
    ys = [r.get('intensity', 0) for r in pain_history]

    plt.figure(figsize=(4, 2.5))
    plt.plot(xs, ys, marker='o')
    plt.title('疼痛强度趋势')
    plt.xlabel('记录')
    plt.ylabel('强度')
    plt.grid(True, linestyle='--', alpha=0.5)

    buf = io.BytesIO()
    plt.tight_layout()
    plt.savefig(buf, format='png')
    plt.close()
    buf.seek(0)
    img_b64 = base64.b64encode(buf.read()).decode('utf-8')
    # 返回 base64 字符串（纯文本），前端可直接作为 data:image/png;base64,...
    return img_b64


@app.route('/record_rehab', methods=['POST'])
def record_rehab():
    print(f"[康复打卡] {datetime.now()} 完成一次训练")
    return 'ok'


@app.route('/doctor_login', methods=['POST'])
def doctor_login():
    data = request.json
    if doctors.get(data.get('id')) == data.get('password'):
        # 返回简单的纯文本：ok|patient1,patient2
        return 'ok|patient001,patient002'
    else:
        return 'fail|'


if __name__ == '__main__':
    app.run(port=5000)
